package com.abe.jmcl.android.retrofit;

import android.os.Bundle;
import android.widget.TextView;

import com.abe.jmcl.R;
import com.abe.jmcl.android.retrofit.contract.XmlCitiesContract;
import com.abe.jmcl.android.retrofit.presenter.XmlCityPresenter;
import com.abe.jmcl.entity.http.city.ChinaEntity;
import com.abe.jmcl.entity.http.city.ProvinceEntity;
import com.abe.jmcl.utils.NormalUtils;
import com.abeframe.core.ConstantCore;
import com.abeframe.core.base.MVPBaseActivity;
import com.google.gson.Gson;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.File;
import java.io.FileReader;
import java.util.List;

import butterknife.BindView;

public class RetrofitXmlActivity extends MVPBaseActivity<XmlCitiesContract.XmlCityView, XmlCityPresenter> implements XmlCitiesContract.XmlCityView {
    @BindView(R.id.item_text_01)
    TextView itemText01;
    @BindView(R.id.item_text_02)
    TextView itemText02;

    @Override
    protected XmlCityPresenter createPresenter() {
        return new XmlCityPresenter();
    }

    @Override
    protected int getThemeResId() {
        return 0;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_retrofit_xml;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected void initDatas() {
        mPresenter.getProvince();
    }

    @Override
    public void onGetProvince(List<ProvinceEntity> entities) {
        try {
            File path = new File(ConstantCore.CACHE_PATH);
            File file = new File(ConstantCore.CACHE_PATH + File.separator + "xmltemp.txt");
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            Serializer serializer = new Persister();
            ChinaEntity chinaEntity = new ChinaEntity();
            chinaEntity.provinces = entities;
            serializer.write(chinaEntity, file);
            FileReader reader=new FileReader(file);
            char[] chs = new char[1024];
            StringBuffer buffer=new StringBuffer();
            while(reader.read(chs) != -1){                                     //每次读1024个字符
                buffer.append(chs);
            }
            itemText01.setText(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        itemText02.setText(new Gson().toJson(entities));
    }

    @Override
    public void showMessage(int Type, String message) {
        NormalUtils.w("Type=" + Type);
        NormalUtils.w("message=" + message);
    }

    @Override
    public void onFaild() {

    }

    @Override
    public void onFaild(String type) {
        NormalUtils.w("onFaild-type=" + type);
    }

    @Override
    public void onFinish(String type) {
        NormalUtils.w("onFinish-type=" + type);
    }
}
